package com.mlink.ai.chat.utils

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class GridSpacingItemDecoration(
    private val spanCount: Int = 2,
    private val spacingBetweenColumns: Int,
    private val spacingBetweenRows: Int,
    private val includeEdge: Boolean = false
) :
    RecyclerView.ItemDecoration() {
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position: Int = parent.getChildAdapterPosition(view) // item position
        if (includeEdge) {
            outRect.left =
                spacingBetweenColumns - position % spanCount * spacingBetweenColumns / spanCount
            outRect.right = (position % spanCount + 1) * spacingBetweenColumns / spanCount
            if (position < spanCount) { // top edge
                outRect.top = spacingBetweenRows
            }
            outRect.bottom = spacingBetweenRows // item bottom
        } else {
            outRect.left = position % spanCount * spacingBetweenColumns / spanCount
            outRect.right =
                spacingBetweenColumns - (position % spanCount + 1) * spacingBetweenColumns / spanCount
            if (position >= spanCount) {
                outRect.top = spacingBetweenRows // item top
            }
        }
    }
}
